package com.flyzing.genl;

import java.util.List;

import com.flyzing.genl.dao.DBConnFactory;
import com.flyzing.genl.dao.TablesDAO;
import com.flyzing.genl.po.ColumnPO;
import com.flyzing.genl.po.TablePO;
import com.flyzing.genl.service.GenBaseMapperFile;
import com.flyzing.genl.service.GenBaseMapperParamsFile;
import com.flyzing.genl.service.GenMapperFile;
import com.flyzing.genl.service.GenMapperXMLFile;
import com.flyzing.genl.service.GenPOFile;
import com.flyzing.genl.service.IGenFile;
import com.flyzing.genl.util.GenConfigHelper;
import com.flyzing.genl.util.StringUtil;

/**
 * 生成
 * 
 * @author yaoguangyao
 * @Date 2020年12月30日
 */
public class GenLight {

	private IGenFile[] genFiles = { new GenPOFile(), 
			new GenBaseMapperFile(), 
			new GenMapperXMLFile(), 
			new GenBaseMapperParamsFile(),
			new GenBaseMapperFile(),
			new GenMapperFile()};

	public GenLight(String configPath) {
		GenConfigHelper.parseConfig(configPath);
	}

	/**
	 * 生成
	 */
	public void generate() {
		String driverName = GenConfigHelper.getProperty("jdbc.driverName");
		String url = GenConfigHelper.getProperty("jdbc.url");
		String username = GenConfigHelper.getProperty("jdbc.username");
		String password = GenConfigHelper.getProperty("jdbc.password");

		DBConnFactory dbConnFactory = DBConnFactory.getInstance(driverName, url, username, password);
		TablesDAO tablesDAO = new TablesDAO(dbConnFactory);
		String schema = GenConfigHelper.getProperty("table.schema");
		String prefix = GenConfigHelper.getProperty("table.prefix", null);
		String tableNames = GenConfigHelper.getProperty("table.names", null);
		
		List<TablePO> tables = null;
		if (StringUtil.isNotNull(prefix)) { //table.prefix，table.names 不能同时为空
			tables = tablesDAO.getTablesByPrefix(schema, prefix);
		} else if(StringUtil.isNotNull(tableNames)) {
			String[] names = tableNames.split(",");
			if (names != null && names.length > 0) {
				tables = tablesDAO.getTablesByNames(schema, names);
			}
		}
		
		if (tables != null && tables.size() > 0) {
			for (TablePO table : tables) {
				List<ColumnPO> columns = tablesDAO.getColumnsByTableName(table);
				for (IGenFile genFile : genFiles) {
					genFile.generate(table, columns);
				}
			}
			System.out.println("SUCCESS<!-- O(∩_∩)O -->");
		} else {
			throw new RuntimeException("没有找到匹配table.prefix和table.names的table");
		}
	}
}
